package com.zhiyou100.util.mybatis;

import cn.hutool.core.util.ObjectUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author yang
 * @className MyBatis
 * @packageName com.zhiyou100.util.mybatis
 * @Description TODO mybatis 工具类 实现 AutoCloseable 接口
 * @date 2020-08-12 20:52
 */
public class MyBatis implements AutoCloseable {

    private static final Logger log = Logger.getLogger(MyBatis.class);

    /**
     * 私有静态变量 记录 SqlSession
     */
    private static SqlSession sqlSession = null;
    private static SqlSessionFactory factory = null;

    static {
        try {
            InputStream resourceAsFile = Resources.getResourceAsStream("mybatis-config.xml");

            final SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

            factory = sqlSessionFactoryBuilder.build(resourceAsFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * @return org.apache.ibatis.session.SqlSession
     * @Description TODO 获取连接
     * @name get
     * @param: []
     * @date 8/12/20 21:04
     * @author yang
     */
    public static SqlSession get() {
        try {
            // 设置自动提交 autoCommit
            sqlSession = factory.openSession(true);
            return sqlSession;
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }


    public static SqlSession get(boolean flag) {
        try {
            // 设置自动提交 autoCommit
            sqlSession = factory.openSession(flag);
            return sqlSession;
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }

    /**
     * @return void
     * @Description TODO 实现 AutoCloseable 自动关流
     * @name close
     * @param: []
     * @date 8/12/20 21:04
     * @author yang
     */
    @Override
    public void close() throws Exception {
        log.info("MyBatis" + "老子关闭了");
        if (!ObjectUtil.isEmpty(sqlSession)) {
            sqlSession.close();
        }

    }
}
